import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { Spin } from 'antd';
import { history } from 'umi';
import type { RunTimeLayoutConfig } from 'umi';
import ScaleLoader from 'react-spinners/ScaleLoader';
import RightContent from '@/components/RightContent';
// import Footer from '@/components/Footer';
import settings from '../config/theme';
// import MIcon from './components/MIcon';

import styles from './app.less';

import registerSulaPlugins from '@/sula-plugin';
import { authSdk, FROM_URL_KEY, TOKEN_KEY } from './utils/auth';
// import { queryCurrentUser, queryToken } from './services/global/base';
import type { CurrentUser } from './services/global/type';
// import { deleteUrlQuery } from './utils/utils';
// import qs from 'qs';

// const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/login';

registerSulaPlugins();
Spin.setDefaultIndicator(
  <ScaleLoader color={settings['primary-color']} height={25} width={2} radius={2} margin={2} />,
);

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: (
    <Spin wrapperClassName="initialLoading">
      <div className="loadingPlaceholder" />
    </Spin>
  ),
};

// const getToken = async () => {
//   let { search } = window.location;
//   if (search.length > 0) {
//     search = search.slice(1);
//   }
//   const data = qs.parse(search);
//   if (data.code) {
//     try {
//       const fromUrl = localStorage.getItem(FROM_URL_KEY);
//       const res = await queryToken(data.code as string);
//       localStorage.setItem(TOKEN_KEY, res.data);
//       const newUrl = deleteUrlQuery(window.location.href, 'code');
//       // 删除url中的code参数
//       // window.history.replaceState({}, '', fromUrl || newUrl);
//       window.location.href = fromUrl || newUrl;
//     } catch (err) {
//       console.log(err);
//     }
//   }
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: CurrentUser;
  fetchUserInfo?: any;
  codeList?: string[];
}> {
  const fetchUserInfo = async () => {
    try {
      // localStorage.setItem('code', 'notPass');
      // const res = await queryCurrentUser();
      // if (res.code === '0') {
      //   localStorage.setItem('code', 'pass');
      // }
      // const currentUser = res.data;
      // return {
      //   ...currentUser,
      //   name: currentUser.staffName,
      // }; // 这个后面开始鉴权后再放开，现在先让他跳转到首页
      // throw new Error('query current user failed');

      const currentUserName: any = localStorage.getItem('user');
      return {
        name: currentUserName,
      }
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  const currentToken = localStorage.getItem(TOKEN_KEY);
  if (!currentToken) {
    history.push(loginPath);
  } else {
    history.push('/');
  }

  const currentUser = await fetchUserInfo();

  // if (window.location.host.includes('tmeoa') && !currentToken) {
  //   await getToken();
  // }
  // 在这行代码之前不能做任何请求，不然都会请求失败--------umi的拦截器是在getInitialState方法后面同步执行的，如果这里直接用同步请求
  // 会导致请求没有被umi的拦截，没有加入token和登陆重新登陆逻辑，在这行代码之后请求就会因为这个代码本身是个异步操作，在nexttick执行，
  // 间接让这行代码后面的代码作为一个微任务加到js的调度任务里，而后面同步执行的umi拦截器挂载就会起作用

  // if (currentUser) {
  //   localStorage.setItem('user', currentUser.staffName);
  //   if (currentUser.orgName) {
  //     localStorage.setItem('organization', currentUser.orgName);
  //   }
  // }

  // 打开权限
  try {
    await authSdk.start();
  } catch (e) {
    console.log(e);
  }
  // // 禁用权限功能功能
  // authSdk.setAble(false);
  // 临时的兜底方案
  const { REACT_APP_ENV } = process.env;
  if (window.location.search.includes('?authLock=true') && REACT_APP_ENV === 'test') {
    console.error('警告，临时兜底方案已启动');
    authSdk.setAble(false);
  }
  return {
    fetchUserInfo,
    currentUser,
    settings: {},
    codeList: authSdk?.codeList,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    logo: (
      <div className={styles.logo}>
        {/* <MIcon type="icon-tme" className={styles.logoIcon} /> */}
        <div className={styles.title}><img src={require('./images/logo.svg')} className={styles.icon} />JAVA判题系统</div>
      </div>
    ),
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      // content: initialState?.currentUser?.staffName,
      content: initialState?.currentUser?.staffName,
      markStyle: { opacity: 0.3 },
    },
    // footerRender: () => <Footer />,
    onPageChange: () => { },
    menuDataRender: (menuData: any[]) => {
      // 根据权限过滤菜单栏
      return authSdk.routerFilter(menuData);
    },
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
